package com.cms.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cms.domain.Feedback;
import com.cms.entity.Category;
import com.cms.entity.Content;
import com.cms.entity.ModelField;
import com.cms.entity.Tag;
import com.cms.service.CategoryService;
import com.cms.service.ContentService;
import com.cms.service.ModelFieldService;
import com.cms.service.TagService;
import com.cms.utils.WebUtils;
import com.cms.utils.PinYinUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.*;


/**
 * Controller - 内容
 * 
 * 
 * 
 */
@Controller("adminContentController")
@RequestMapping("/admin/content")
public class ContentController extends BaseController {

	@Autowired
	private ContentService contentService;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private TagService tagService;

	@Autowired
	private ModelFieldService modelFieldService;

	/**
	 * 列表
	 */
	@RequestMapping
	public String index(ModelMap modelMap){
		modelMap.addAttribute("categoryTree", categoryService.findTree(null,getCurrentSite().getId()));
	    return getView("content/index");
	}

	/**
	 * 标签
	 */
	@RequestMapping("/tag")
	public String tag(ModelMap modelMap){
		modelMap.addAttribute("tags",tagService.findAll());
		return getView("content/tag");
	}

	/**
	 * 添加
	 */
	@RequestMapping("/add")
	public String add(Integer categoryId,ModelMap modelMap) {
		Category category = categoryService.getById(categoryId);
	    List<ModelField> modelFields = modelFieldService.findList(category.getModelId());
		modelMap.addAttribute("categoryTree", categoryService.findTree(null,getCurrentSite().getId()));
		modelMap.addAttribute("modelFields", modelFields);
		modelMap.addAttribute("category", category);
		return getView("content/add");
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Feedback save(Content content, String[] chunkValues) {
		boolean checkCode = contentService.checkCode(content.getCode(),content.getId(),getCurrentSite().getId());
		if(!checkCode){
			return Feedback.error("编码已存在");
		}
		Integer modelId = content.getCategory().getModelId();
		List<ModelField> modelFields = modelFieldService.findList(modelId);
		Map<String,Object> model = new HashMap<String,Object>();
		for(ModelField modelField : modelFields){
		    if("multipleFile".equals(modelField.getType())){
                model.put(modelField.getName(), WebUtils.getRequest().getParameterValues(modelField.getName()));
            }else{
                model.put(modelField.getName(), WebUtils.getRequest().getParameter(modelField.getName()));
            }
		}
		if(ArrayUtils.isNotEmpty(chunkValues)){
			content.setChunkValue(JSONArray.toJSONString(chunkValues));
		}else{
			content.setChunkValue(JSONArray.toJSONString(new String[]{}));
		}
		//轮播多图
		String[] picValues = WebUtils.getRequest().getParameterValues("picValues");
		if(ArrayUtils.isNotEmpty(picValues)){
			content.setPicValue(JSONArray.toJSONString(picValues));
		}else{
			content.setPicValue("");
		}
		//标签
		String[] tagNames = WebUtils.getRequest().getParameterValues("tagNames");
		if(ArrayUtils.isNotEmpty(tagNames)){
			List<Integer> tagIds = new ArrayList<>();
			for(String tagName : tagNames){
				Tag tag = tagService.findByName(tagName);
				if(tag==null){
					tag = new Tag();
					tag.setName(tagName);
					tag.setCat(PinYinUtils.convertLower(tagName));
					tag.setCreateDate(LocalDateTime.now());
					tag.setUpdateDate(LocalDateTime.now());
					tagService.save(tag);
				}
				tagIds.add(tag.getId());
			}
			content.setTagIdValue(","+ StringUtils.join(tagIds,",")+",");
		}else{
			content.setTagIdValue("");
		}
		content.setModelFieldValue(JSONObject.toJSONString(model));
		content.setSiteId(getCurrentSite().getId());
		content.setCreateDate(LocalDateTime.now());
		content.setUpdateDate(LocalDateTime.now());
		contentService.save(content);
		return Feedback.success(new HashMap<>());
	}

	/**
	 * 编辑
	 */
	@RequestMapping("/edit")
	public String edit(Integer id,ModelMap modelMap) {
		Content content = contentService.getById(id);
		Category category = categoryService.getById(content.getCategoryId());
        List<ModelField> modelFields = modelFieldService.findList(category.getModelId());
		modelMap.addAttribute("categoryTree", categoryService.findTree(null,getCurrentSite().getId()));
		modelMap.addAttribute("category", category);
		modelMap.addAttribute("modelFields", modelFields);
		modelMap.addAttribute("content", content);
		return getView("content/edit");
	}

	/**
	 * 更新
	 */
	@ResponseBody
	@RequestMapping("/update")
	public Feedback update(Content content,String[] chunkValues) {
		boolean checkCode = contentService.checkCode(content.getCode(),content.getId(),getCurrentSite().getId());
		if(!checkCode){
			return Feedback.error("编码已存在");
		}
		Integer modelId = content.getCategory().getModelId();
		List<ModelField> modelFields = modelFieldService.findList(modelId);
		Map<String,Object> model = new HashMap<String,Object>();
		for(ModelField modelField : modelFields){
		    if("multipleFile".equals(modelField.getType())){
		        model.put(modelField.getName(), WebUtils.getRequest().getParameterValues(modelField.getName()));
		    }else{
		        model.put(modelField.getName(), WebUtils.getRequest().getParameter(modelField.getName()));
		    }
		}
		if(ArrayUtils.isNotEmpty(chunkValues)){
			content.setChunkValue(JSONArray.toJSONString(chunkValues));
		}else{
			content.setChunkValue(JSONArray.toJSONString(new String[]{}));
		}
		//轮播多图
		String[] picValues = WebUtils.getRequest().getParameterValues("picValues");
		if(ArrayUtils.isNotEmpty(picValues)){
			content.setPicValue(JSONArray.toJSONString(picValues));
		}else{
			content.setPicValue("");
		}
		//标签
		String[] tagNames = WebUtils.getRequest().getParameterValues("tagNames");
		if(ArrayUtils.isNotEmpty(tagNames)){
			List<Integer> tagIds = new ArrayList<>();
			for(String tagName : tagNames){
				Tag tag = tagService.findByName(tagName);
				if(tag==null){
					tag = new Tag();
					tag.setName(tagName);
					tag.setCat(PinYinUtils.convertLower(tagName));
					tag.setCreateDate(LocalDateTime.now());
					tag.setUpdateDate(LocalDateTime.now());
					tagService.save(tag);
				}
				tagIds.add(tag.getId());
			}
			content.setTagIdValue(","+ StringUtils.join(tagIds,",")+",");
		}else{
			content.setTagIdValue("");
		}
		content.setModelFieldValue(JSONObject.toJSONString(model));
		content.setUpdateDate(LocalDateTime.now());
		contentService.updateById(content);
		return Feedback.success(new HashMap<>());
	}
	
	/**
	 * 修改状态
	 */
	@ResponseBody
	@RequestMapping("/updateStatus")
	public Feedback updateStatus(Boolean value,Integer id){
		Integer status = BooleanUtils.toInteger(value);
		Content content = contentService.getById(id);
		content.setStatus(status);
		content.setUpdateDate(LocalDateTime.now());
		contentService.updateById(content);
		return Feedback.success(new HashMap<>());
	}
	
	/**
	 * 修改是否置顶
	 */
	@ResponseBody
	@RequestMapping("/updateIsTop")
	public Feedback updateIsTop(Boolean value,Integer id){
		Content content = contentService.getById(id);
		content.setIsTop(value);
		content.setUpdateDate(LocalDateTime.now());
		contentService.updateById(content);
		return Feedback.success(new HashMap<>());
	}
	
	/**
	 * 修改是否推荐
	 */
	@ResponseBody
	@RequestMapping("/updateIsRecommend")
	public Feedback updateIsRecommend(Boolean value,Integer id){
		Content content = contentService.getById(id);
		content.setIsRecommend(value);
		content.setUpdateDate(LocalDateTime.now());
		contentService.updateById(content);
		return Feedback.success(new HashMap<>());
	}
	
	/**
	 * 修改是否头条
	 */
	@ResponseBody
	@RequestMapping("/updateIsHeadline")
	public Feedback updateIsHeadline(Boolean value,Integer id){
		Content content = contentService.getById(id);
		content.setIsHeadline(value);
		content.setUpdateDate(LocalDateTime.now());
		contentService.updateById(content);
		return Feedback.success(new HashMap<>());
	}
	
   /**
     * 修改排序
     */
   	@ResponseBody
   	@RequestMapping("/updateSort")
    public Feedback updateSort(String sortArray){
        JSONArray jsonArray = JSONArray.parseArray(sortArray);
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Integer id = jsonObject.getInteger("id");
            Integer sort = jsonObject.getInteger("sort");
            Content content = contentService.getById(id);
            content.setSort(sort);
			contentService.updateById(content);
        }
		return Feedback.success(new HashMap<>());
    }
	
	/**
	 * 数据
	 */
	@RequestMapping("/data")
	public String data(String title,Integer categoryId,Integer pageNumber,ModelMap modelMap) {
		setListQuery();
		if(pageNumber==null){
			pageNumber = 1;
		}
		modelMap.addAttribute("categoryId",categoryId);
		modelMap.addAttribute("page", contentService.findPage(categoryId,title,pageNumber,PAGE_SIZE,getCurrentSite().getId()));
		modelMap.addAttribute("title", title);
		return getView("content/data");
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public Feedback delete(Integer[] ids) {
		contentService.removeByIds(Arrays.asList(ids));
		return Feedback.success(new HashMap<>());
	}

}